using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Globalization;
using System.Windows.Forms;
using Microsoft.WowAddonStudio.FrameXml.Serialization;
using Microsoft.WowAddonStudio.FrameXml.Serialization.Support;

namespace Microsoft.WowAddonStudio.FrameXml.Components.Editors
{
	/// <summary>
	/// 
	/// </summary>
	public class InheritanceEditorUI<TInheritableObject> : ControlSelectorUI where TInheritableObject : InheritableObject
	{
		private readonly IFrameXmlControl frameControl;

		/// <summary>
		/// Initializes a new instance of the <see cref="ControlSelectorUI"/> class.
		/// </summary>
		/// <param name="provider">The provider.</param>
		/// <param name="frameObject">The frame object.</param>
		public InheritanceEditorUI(IServiceProvider provider, IFrameXmlControl frameObject)
			: base(provider, false, frameObject as Control)
		{
			if (frameObject == null)
				throw new ArgumentNullException("frameObject");

			frameControl = frameObject;
			FillControls();
		}


		/// <summary>
		/// Fills the controls.
		/// </summary>
		protected override void FillControls()
		{
			if (frameControl != null)
			{
				var service = GetService<IDesignerHost>(typeof(IDesignerHost));
				if (service != null)
				{
					try
					{
						//Gets the name of the SerializationObject
						string typeName = frameControl.SerializationObject.
							GetType().Name.ToLower(CultureInfo.InvariantCulture);

						BeginUpdate();

						//Add empty item first
						Items.Add(String.Empty);

						//Add existing controls, except the selected
						AddControls(service.RootComponent as Control);

						//Get all inheritable template names
                        IEnumerable<string> names = FrameXmlDirectory.Default.GetNames<TInheritableObject>();

						//Iterate through all template names
						foreach (var name in names)
						{
							//Add only related templates by its name
							if (name.ToLower(CultureInfo.InvariantCulture).Contains(typeName))
								Items.Add(name);
						}
					}
					finally
					{
						EndUpdate();
					}
				}
			}
		}

		/// <summary>
		/// Inits the controls.
		/// </summary>
		/// <param name="component">The component.</param>
		protected override void AddControls(Control component)
		{
			if (component == null) return;

			if (component is LayoutFrameControl && frameControl != component)
				Items.Add(component.Name);

			if (component.Controls.Count > 0)
			{
				foreach (Control control in component.Controls)
					AddControls(control);
			}
		}

	}
}